import React from "react";
import HButton, {HButtonProps} from "@/components/ant-ext/HButton";
import {ActionType, SetLoadingType} from "@/common/httptypes";
import {Empower} from "@/components/ant-ext/empower";
import {ButtonProps} from "antd";


export type HActionProps = Empower & ButtonProps & {
    action?: (setLoading: SetLoadingType) => void
    confirm?: { title: string, ok?: ActionType, cancel?: ActionType } | string
}
export default class HAction extends React.Component<HActionProps, any> {

    state: {
        action?: (setLoading: SetLoadingType) => void, setLoading: SetLoadingType, loading: boolean,
        confirm?: HButtonProps["confirm"]
    } = {
        setLoading: (loading) => {
            this.setState({loading})
        },
        loading: false,
        confirm: undefined

    }

    constructor(props: HActionProps) {
        super(props);
        const {action, confirm} = props;

        if (confirm !== undefined) {
            this.state.confirm = this.bindConfirm()
        } else {
            this.state.action = action
        }
    }

    componentDidUpdate(prevProps: Readonly<HActionProps>, prevState: Readonly<any>, snapshot?: any) {
        if (this.props.confirm !== prevProps.confirm) {
            this.setState({confirm: this.bindConfirm()})
        }
        if (this.props.action !== prevProps.action) {
            if (this.props.action !== undefined && this.props.confirm === undefined) {
                this.setState({action: this.props.action})
            }
        }

    }

    bindConfirm() {
        const {confirm, action} = this.props;

        if (confirm) {
            if (typeof confirm === "string") {
                return {
                    title: confirm,
                    ok: () => {
                        action?.(this.state.setLoading)
                    }, cancel: () => {
                    }
                }

            } else {
                return {
                    title: confirm.title,
                    ok: () => {
                        confirm?.ok?.(this.state.setLoading)
                    }, cancel: () => {
                        confirm?.cancel?.(this.state.setLoading)
                    }
                }
            }
        }

    }


    render() {
        const {loading, setLoading} = this.state;
        const {action, ...other} = this.props
        return <HButton {...other} confirm={this.state.confirm} loading={loading} onClick={() => {
            this.state.action?.(setLoading)
        }}/>;
    }
}